--[[
	设置界面
	2015_12_03 C.P
	功能：音乐音量震动等
]]

local OptionLayer = class("OptionLayer", function(scene)
		local optionLayer = display.newLayer(cc.c4b(0, 0, 0, 125))
    return optionLayer
end)
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local g_var = ExternalFun.req_var
local WebViewLayer = appdf.CLIENT_SRC .. "plaza.views.layer.plaza.WebViewLayer"
-- appdf.req(appdf.CLIENT_SRC.."plaza.models.FriendMgr")
local NotifyMgr = appdf.req(appdf.EXTERNAL_SRC .. "NotifyMgr")
local ModifyFrame = appdf.req(appdf.CLIENT_SRC.."plaza.models.ModifyFrame")

OptionLayer.CBT_SILENCE 	= 1
OptionLayer.CBT_SOUND   	= 2
OptionLayer.BT_EXIT			= 7

OptionLayer.BT_QUESTION		= 8
OptionLayer.BT_COMMIT		= 9
OptionLayer.BT_MODIFY		= 10
OptionLayer.BT_EXCHANGE		= 11
OptionLayer.BT_LOCK         = 12
OptionLayer.BT_UNLOCK       = 13

OptionLayer.BT_SWITCH       = 14
OptionLayer.BT_CLEAR        = 15
OptionLayer.PRO_WIDTH		= yl.WIDTH

function OptionLayer:ctor(scene)
	self._scene = scene
	self:setContentSize(yl.WIDTH,yl.HEIGHT)
	local this = self

    local cbtlistener = function (sender,eventType)
    	this:onSelectedEvent(sender:getTag(),sender,eventType)
    end
	local  btcallback = function(ref, type)
        if type == ccui.TouchEventType.ended then
         	this:onButtonClickedEvent(ref:getTag(),ref)
        end
    end

	local areaWidth = yl.WIDTH
	local areaHeight = yl.HEIGHT

	
    local rootLayer, csbNode = ExternalFun.loadRootCSB("popView/setLayer.csb", self)
	self.csbNode = csbNode
    csbNode:getChildByName("closebt")
        :setTag(OptionLayer.BT_EXIT)
        :addTouchEventListener(btcallback)

       local bt= csbNode:getChildByName("Button_1")
         bt:setTag(OptionLayer.BT_EXCHANGE)
         bt:addTouchEventListener(btcallback)
	--	bt:setVisible(false)	
		csbNode:getChildByName("Button_1_0")
       :setTag(OptionLayer.BT_CLEAR)
       :addTouchEventListener(btcallback)
	
		
	local yy_kaibt =  csbNode:getChildByName("yy_kai")
	local yx_kaibt =  csbNode:getChildByName("yx_kai")
	local yy_guangbt =  csbNode:getChildByName("yy_guang")
	local yx_guangbt =  csbNode:getChildByName("yx_guang")
	
	local yy_text = csbNode:getChildByName("yy_text")
	local yx_text = csbNode:getChildByName("yx_text")
	
	yy_kaibt:addTouchEventListener(function (ref,type)
		if type == ccui.TouchEventType.ended then
			ref:setVisible(false)
			yy_guangbt:setVisible(true)
			GlobalUserItem.setVoiceAble(false)
			ExternalFun.playPlazzBackgroudAudio()
			yy_text:setString("音乐：关")
		end
	end)
	
	yx_kaibt:addTouchEventListener(function (ref,type)
		if type == ccui.TouchEventType.ended then
			ref:setVisible(false)
			yx_guangbt:setVisible(true)
			GlobalUserItem.setSoundAble(false)
			yx_text:setString("音效：关")
		end
	end)
	
	yy_guangbt:addTouchEventListener(function (ref,type)
		if type == ccui.TouchEventType.ended then
			ref:setVisible(false)
			yy_kaibt:setVisible(true)
			yy_text:setString("音乐：开")
			GlobalUserItem.setVoiceAble(true)
            ExternalFun.playPlazzBackgroudAudio()
		end
	end)
	
	yx_guangbt:addTouchEventListener(function (ref,type)
		if type == ccui.TouchEventType.ended then
			ref:setVisible(false)
			yx_kaibt:setVisible(true)
			GlobalUserItem.setSoundAble(true)
			yx_text:setString("音效：开")
		end
	end)
	if GlobalUserItem.bVoiceAble then
		yy_kaibt:setVisible(true)
		yy_guangbt:setVisible(false)
		yy_text:setString("音乐：开")
	else
		yy_kaibt:setVisible(false)
		yy_guangbt:setVisible(true)
		yy_text:setString("音乐：关")
	end
	
	if GlobalUserItem.bSoundAble then
		yx_kaibt:setVisible(true)
		yx_guangbt:setVisible(false)
		yx_text:setString("音效：开")
	else
		yx_kaibt:setVisible(false)
		yx_guangbt:setVisible(true)
		yx_text:setString("音效：关")
	end
    -- csbNode:getChildByName("Button_1")
    --     :setTag(OptionLayer.BT_SWITCH)
    --     :addTouchEventListener(btcallback)
	
--	self._cbtSilence = ccui.CheckBox:create("popView/bt_option_switch_0.png","","popView/bt_option_switch_1.png","","")
--		:move(685,461)
--		:setSelected(GlobalUserItem.bSoundAble)
--		:addTo(self)
--		:setTag(self.CBT_SOUND)
--	self._cbtSilence:addEventListener(cbtlistener)
--
--
--	self._cbtSound = ccui.CheckBox:create("popView/bt_option_switch_0.png","","popView/bt_option_switch_1.png","","")
--		:move(685,357)
--		:setSelected(GlobalUserItem.bVoiceAble)
--		:addTo(self)
--		:setTag(self.CBT_SILENCE)
--	self._cbtSound:addEventListener(cbtlistener)

    local mgr = self._scene:getApp():getVersionMgr()

    local localver = cc.UserDefault:getInstance():getIntegerForKey("extra_command_version", 0)
    -- 版本号
   cc.Label:createWithTTF("版本号:" ..localver.."_".. (mgr:getResVersion() or 0).."_"..(appdf.BASE_C_RESVERSION or 0).."("..(appdf.BASE_C_VERSION or 0)..")"..(appdf.channelId or 0), "fonts/round_body.ttf", 24)
       :move(yl.WIDTH,0)
       :setAnchorPoint(cc.p(1,0))
       :addTo(self)

end
function OptionLayer:hideChangeAccount()
	local changebt = self.csbNode:getChildByName("Button_1")
	changebt:setVisible(false)
	local clearbt = self.csbNode:getChildByName("Button_1_0")
	clearbt:setPositionX(clearbt:getPositionX()+200)
	clearbt:setVisible(not appdf.APPSTORE_VERSION)
end

function OptionLayer:onSelectedEvent(tag,sender,eventType)
	if tag == OptionLayer.CBT_SILENCE then
		GlobalUserItem.setVoiceAble(eventType == 0)
		--背景音乐
        ExternalFun.playPlazzBackgroudAudio()
	elseif tag == OptionLayer.CBT_SOUND then
		GlobalUserItem.setSoundAble(eventType == 0)
	end
end

--按键监听
function OptionLayer:onButtonClickedEvent(tag,sender)
	if tag ~= OptionLayer.BT_EXCHANGE and tag ~= OptionLayer.BT_EXIT then
		if GlobalUserItem.isAngentAccount() then
			return
		end
	end	
    local fileUtil = cc.FileUtils:getInstance()
    if tag == OptionLayer.BT_EXCHANGE then
        if device.platform ~= "windows" then
            fileUtil:removeFile(device.writablePath.."UserDefault.xml")
        end
        fileUtil:removeFile(device.writablePath .."myMail.txt")
        fileUtil:removeFile(device.writablePath.."kefuFeedback.json")
        fileUtil:removeFile(device.writablePath.."user_gameconfig.plist")
		fileUtil:removeFile(device.writablePath .."noticeMail.txt")
		
        -- cc.UserDefault:getInstance():setStringForKey("account","")
        -- cc.UserDefault:getInstance():setStringForKey("pwd","")
        GlobalUserItem.onSaveAccountConfig()
        cc.UserDefault:getInstance():flush()
        self._scene:releasePublicRes()
        self._scene:ExitClient()
    elseif tag == OptionLayer.BT_CLEAR then
		local hasDeletCount = 0
 
        if device.platform ~= "windows" then
           

            fileUtil:removeFile(device.writablePath.."user_gameconfig.plist")
            fileUtil:removeFile(device.writablePath.."UserDefault.xml")
            fileUtil:removeFile(device.writablePath .."Allmail.txt")
            fileUtil:removeFile(device.writablePath.."bankHistory.json")
            fileUtil:removeFile(device.writablePath.."baseupdate/client/filemd5List.json")
            fileUtil:removeDirectory(device.writablePath.."download/")
            fileUtil:removeFile(device.writablePath.."version.plist")
            fileUtil:removeDirectory(device.writablePath.."command/")
            cc.UserDefault:getInstance():setIntegerForKey("extra_command_version", 0)
            cc.UserDefault:getInstance():setStringForKey("account","")
            cc.UserDefault:getInstance():setStringForKey("pwd","")
            cc.UserDefault:getInstance():setIntegerForKey("maxMailId", 1)
            cc.UserDefault:getInstance():flush()
        end
        appdf.reloadClient =  false
        self._scene:releasePublicRes()
        yl.updateList = {}
        GlobalUserItem.szInputBanekrPassword = nil
        showToast(self,"清理成功,请重新启动游戏",2)
        AudioEngine.stopMusic()
        cc.SimpleAudioEngine:getInstance():stopMusic()
        if  device.platform == "ios" then
            self._scene:getApp():enterSceneEx("plaza.views.WelcomeScene","FADE",1)
        else
            -- fileUtil:removeDirectory(device.writablePath.."baseupdate/")
            require("app.MyApp"):create():run()
        end

	elseif tag == OptionLayer.BT_EXIT then
		self._scene:onKeyBack()
    elseif tag == OptionLayer.BT_SWITCH then
		-- self._scene:onKeyBack()
        -- local luaoc = require "cocos.cocos2d.luaoc"
        -- luaoc.callStaticMethod("AppController","switchAccount")
	elseif tag == OptionLayer.BT_QUESTION then
		self._scene:onChangeShowMode(yl.SCENE_FAQ)
	elseif tag == OptionLayer.BT_MODIFY then
        if self._scene._gameFrame:isSocketServer() then
            showToast(self,"当前页面无法使用此功能！",1)
            return
        end
		self._scene:onChangeShowMode(yl.SCENE_MODIFY)
	elseif tag == OptionLayer.BT_COMMIT then
		self._scene:onChangeShowMode(yl.SCENE_FEEDBACK)
    elseif tag == OptionLayer.BT_LOCK then
        print("锁定机器")
        self:showLockMachineLayer(self)
    elseif tag == OptionLayer.BT_UNLOCK then
        print("解锁机器")
        self:showLockMachineLayer(self)
	end
end

local TAG_MASK = 101
local BTN_CLOSE = 102
function OptionLayer:showLockMachineLayer( parent )
    if nil == parent then
        return
    end
    --网络回调
    local modifyCallBack = function(result,message)
        self:onModifyCallBack(result,message)
    end
    --网络处理
    self._modifyFrame = ModifyFrame:create(self,modifyCallBack)

    -- 加载csb资源
    local csbNode = ExternalFun.loadCSB("Option/LockMachineLayer.csb", parent )

    local touchFunC = function(ref, tType)
        if tType == ccui.TouchEventType.ended then
            local tag = ref:getTag()
            if TAG_MASK == tag or BTN_CLOSE == tag then
                csbNode:removeFromParent()
            elseif OptionLayer.BT_LOCK == tag then
                local txt = csbNode.m_editbox:getText()
                if txt == "" then
                    showToast(self, "密码不能为空!", 2)
                    return 
                end
                self._modifyFrame:onBindingMachine(1, txt)
                csbNode:removeFromParent()
            elseif OptionLayer.BT_UNLOCK == tag then
                local txt = csbNode.m_editbox:getText()
                if txt == "" then
                    showToast(self, "密码不能为空!", 2)
                    return 
                end
                self._modifyFrame:onBindingMachine(0, txt)
                csbNode:removeFromParent()
            end
        end
    end

    -- 遮罩
    local mask = csbNode:getChildByName("panel_mask")
    mask:setTag(TAG_MASK)
    mask:addTouchEventListener( touchFunC )

    local image_bg = csbNode:getChildByName("image_bg")
    image_bg:setSwallowTouches(true)

    -- 输入
    local tmp = image_bg:getChildByName("sp_lockmachine_bankpw")
    local editbox = ccui.EditBox:create(cc.size(tmp:getContentSize().width - 10, tmp:getContentSize().height - 10),"blank.png",UI_TEX_TYPE_PLIST)
        :setPosition(tmp:getPosition())
        :setFontName("fonts/round_body.ttf")
        :setPlaceholderFontName("fonts/round_body.ttf")
        :setFontSize(30)
        :setPlaceholderFontSize(30)
        :setMaxLength(32)
        :setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD)
        :setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE)
        :setPlaceHolder("请输入密码")
    image_bg:addChild(editbox)
    csbNode.m_editbox = editbox

    -- 锁定/解锁
    local btn = image_bg:getChildByName("btn_lock")
    btn:setTag(OptionLayer.BT_LOCK)
    btn:addTouchEventListener( touchFunC )
    local normal = "Option/btn_lockmachine_0.png"
    local disable = "Option/btn_lockmachine_0.png"
    local press = "Option/btn_lockmachine_1.png"
    if 1 == GlobalUserItem.cbLockMachine then
        btn:setTag(OptionLayer.BT_UNLOCK)
        normal = "Option/btn_unlockmachine_0.png"
        disable = "Option/btn_unlockmachine_0.png"
        press = "Option/btn_unlockmachine_1.png"
    end
    btn:loadTextureDisabled(disable)
    btn:loadTextureNormal(normal)
    btn:loadTexturePressed(press)  

    btn = image_bg:getChildByName("btn_cancel")
    btn:setTag(BTN_CLOSE)
    btn:addTouchEventListener( touchFunC )

    -- 关闭
    btn = image_bg:getChildByName("btn_close")
    btn:setTag(BTN_CLOSE)
    btn:addTouchEventListener( touchFunC )
end

function OptionLayer:onModifyCallBack(result, tips)
    if type(tips) == "string" and "" ~= tips then
        showToast(self, tips, 2)
    end 

    local normal = "Option/btn_lockmachine_0.png"
    local disable = "Option/btn_lockmachine_0.png"
    local press = "Option/btn_lockmachine_1.png"
    if self._modifyFrame.BIND_MACHINE == result then
        if 0 == GlobalUserItem.cbLockMachine then
            GlobalUserItem.cbLockMachine = 1
            self.m_btnLock:setTag(OptionLayer.BT_UNLOCK)
            normal = "Option/btn_unlockmachine_0.png"
            disable = "Option/btn_unlockmachine_0.png"
            press = "Option/btn_unlockmachine_1.png"
        else
            GlobalUserItem.cbLockMachine = 0
            self.m_btnLock:setTag(OptionLayer.BT_LOCK)
        end
    end   
    self.m_btnLock:loadTextureDisabled(disable)
    self.m_btnLock:loadTextureNormal(normal)
    self.m_btnLock:loadTexturePressed(press)  
end

return OptionLayer